package com.ljw.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ljw.common.to.es.SkuEsModel;
import com.ljw.common.utils.R;
import com.ljw.gulimall.search.config.GulimallElasticSearchConfig;
import com.ljw.gulimall.search.constant.EsConstant;
import com.ljw.gulimall.search.feign.ProductFeignService;
import com.ljw.gulimall.search.service.MallSearchService;
import com.ljw.gulimall.search.vo.AttrResponseVo;
import com.ljw.gulimall.search.vo.SearchParam;
import com.ljw.gulimall.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Resource
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    //去es检索
    @Override
    public SearchResult search(SearchParam searchParam) {
        //1、动态构建出查询需要的dsl语句
        //1、准备好检索请求
        SearchResult result = null;
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
            //2、执行检索请求
            SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

            result = buildSearchResult(response, searchParam);
            //3、分析相应数据封装成我们需要的格式
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 准备检索请求
     * #模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        //1、创建检索数据构建器
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //2、封装
        /**
         * 查询：模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // must 模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }

        // filter 过滤分类
        if (searchParam.getCatalog3Id() != null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        // filter 过滤品牌
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        // filter 过滤库存
        if (searchParam.getHasStock() != null){
            boolQuery.filter(QueryBuilders.termsQuery("hasStock", searchParam.getHasStock() == 1));
        }
        // filter 过滤价格区间
        // skuPrice=_500｜500_｜100_500
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String skuPrice = searchParam.getSkuPrice();
            String[] split = skuPrice.split("_");
            if (skuPrice.startsWith("_")){
                rangeQuery.lte(split[1]);
            }
            else if (skuPrice.endsWith("_")){
                rangeQuery.gte(split[0]);
            }
            else {
                rangeQuery.gte(split[0]);
                rangeQuery.lte(split[1]);
            }
            boolQuery.filter(rangeQuery);
        }
        // filter 过滤属性
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0){
            for (String attr : searchParam.getAttrs()) {
                //attrs=1_5寸:8寸｜attrs=2_16G:8G
                String[] split = attr.split("_");
                String attrId = split[0]; //检索属性的id
                String[] attrValues = split[1].split(":"); //检索属性的值，可能有多个
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attr.attrValue", attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                //每一个必须都得生成一个nested查询
                boolQuery.filter(nestedQuery);
            }
        }
        //把以前的所有条件都拿来进行封装
        sourceBuilder.query(boolQuery);

        /**
         * 排序
         */
        if (!StringUtils.isEmpty(searchParam.getSort())){
            String sort = searchParam.getSort();
            //sort=hotScore_asc
            String[] split = sort.split("_");
            SortOrder order = split[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC; //判断排序方式
            sourceBuilder.sort(split[0],order);
        }

        /**
         * 分页
         * pageSize = 5
         * pageNum = 1 from = 0 size = 5; [0,1,2,3,4]
         * pageNum = 2 from = 5 size= 5; [5,6,7,8,9]
         * from = (pageNum-1) * pageSize
         */
        sourceBuilder.from(((searchParam.getPageNum() == null ? 1 : searchParam.getPageNum()) - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);

        /**
         * 高亮
         */
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */
        //1、品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        //品牌的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        //2、分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        //分类的子聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        //3、属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //聚合当前所有的attrId;
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //根据attrId聚合出attrName
        TermsAggregationBuilder attr_name_agg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1);
        //根据attrId聚合出attrValue
        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(1);
        attr_id_agg.subAggregation(attr_name_agg);
        attr_id_agg.subAggregation(attr_value_agg);
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;

    }

    /**
     * 构建结果数据
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam searchParam) {

        SearchHits hits = response.getHits();

        SearchResult result = new SearchResult();
        //1、返回所有查询到的商品
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = new SkuEsModel();
                skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //设置标题高亮
                HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                if (skuTitle != null){
                    skuEsModel.setSkuTitle(skuTitle.getFragments()[0].string());
                }
                skuEsModels.add(skuEsModel);
            }
        }
        result.setProducts(skuEsModels);
        //2、当前所有商品涉及到的属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性的id
            Long attrId = Long.parseLong(bucket.getKeyAsString());
            attrVo.setAttrId(attrId);
            //得到属性的名称
            String attrName = ((ParsedStringTerms)bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            //得到属性的值
            List<? extends Terms.Bucket> attrValueAgg = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets();
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket attrValueBucket : attrValueAgg) {
                String attrValue = attrValueBucket.getKeyAsString();
                attrValues.add(attrValue);
            }
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
        //3、当前所有商品涉及到的品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //得到品牌的id
            brandVo.setBrandId(Long.parseLong(bucket.getKeyAsString()));
            //得到品牌的名字
            String brandName = ((ParsedStringTerms)bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            //得到品牌的图片
            String brandImg = ((ParsedStringTerms)bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        //4、当前所有商品涉及到的分类信息
        ParsedLongTerms catalog_agg =  response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(Long.parseLong(bucket.getKeyAsString()));
            ParsedStringTerms parsedStringTerms = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = parsedStringTerms.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        //5、分页信息-页码，总记录数
        Long total = hits.getTotalHits().value;
        int totalPages = (int)(total % EsConstant.PRODUCT_PAGE_SIZE) == 0 ? (int)(total % EsConstant.PRODUCT_PAGE_SIZE) : (int)(total / EsConstant.PRODUCT_PAGE_SIZE+ 1);
        result.setPageNum(searchParam.getPageNum() == null ? 1 : searchParam.getPageNum());
        result.setTotalPages(totalPages); //页码
        result.setTotal(total); //总记录数
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

//        //6、构建面包屑导航功能
//        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0){
//            List<SearchResult.NavVo> navVos = searchParam.getAttrs().stream().map( attr -> {
//                //1、分析每个attrs传过来的查询参数值。
//                SearchResult.NavVo navVo = new SearchResult.NavVo();
//                String[] s = attr.split("_");
//                navVo.setNavValue(s[1]);
//                R r = productFeignService.info(Long.parseLong(s[0]));
//                if (r.getCode() == 0){
//                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
//                    });
//                    navVo.setNavName(data.getAttrName());
//                }else {
//                    navVo.setNavName(s[0]);
//                }
//
//                //2、取消了这个面包屑以后，我们要跳转到那个地方，将 请求地址的url里面的当前置空
//                //拿到所有的查询条件，去掉当前。
//                searchParam.get_queryString().replace("",)
//                return navVo;
//            }).collect(Collectors.toList());
//        }
//        result.setNavs(navVos);

        return result;
    }
}
